import React, { createRef } from 'react'

import { NavLink } from 'react-router-dom'
import { getLinks } from '../../api/link'

import Sidebar from './sidebar'

import './index.scss'

interface State {
  links: Array<linkTypes>
  toggle: boolean
  popup: boolean
}
interface Props {}
interface linkTypes {
  title: string
  path: string
}

export default class NavBar extends React.Component<Props, State> {
  state = {
    links: [],
    toggle: true,
    popup: false,
  }

  header = createRef()

  componentDidMount() {
    this.setState({
      links: [...getLinks()],
    })

    window.addEventListener('scroll', (e) => {
      if (window.scrollY > 150) {
        this.setState({
          toggle: false,
        })
      } else {
        this.setState({
          toggle: true,
        })
      }
    })
  }

  toggle = () => {
    this.setState({
      popup: !this.state.popup,
    })
  }

  linkRender = (links: Array<any>) => {
    if (!links) return null
    return links.map(({ title, path }) => {
      return (
        <NavLink
          key={path}
          className="nav-link"
          activeClassName="active"
          to={path}
        >
          {title}
        </NavLink>
      )
    })
  }

  render() {
    const { links, toggle, popup } = this.state
    return (
      <>
        <Sidebar popup={this.state.popup} toggle={this.toggle} />
        <header className={`header ${toggle ? 'toggle' : ''}`}>
          <div className="header-wrapper">
            {/* 汉堡按钮 */}
            <div
              className={`barurger ${popup ? 'active' : ''}`}
              onClick={this.toggle}
            >
              <span className="line"></span>
              <span className="line"></span>
              <span className="line"></span>
            </div>
            <div className="author">
              <h1 className="nickname">Redloney</h1>
            </div>
            <nav className="nav">{this.linkRender(links)}</nav>
          </div>
        </header>
      </>
    )
  }
}
